<template>
<div class="page_rela_container">
		<div class="scroll_auto flex_cell">

    <el-form :rules="rules" ref="role_form_panel" :model="formValue" label-width="130px" class="common-form-panel-div">
      <!-- mini small medium -->
      <ex_header_spiler :title="$tt('label_base_info')" style="width: 100%"></ex_header_spiler>
      <el-row>
        <el-col>
          <el-form-item :label="$tt('label_role_name')" prop="name">
            <el-input v-model="formValue.name"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="roleSystemInputShow">
        <el-col :span="2">
          <el-form-item :label="$tt('label_applicable_system')">
            <el-radio-group v-model="roleSystemInput">
              <el-radio v-for="item, index in roleSystemArr" :label="item.id" :key="index">{{ item.name }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="roleScope == 'DEFAULT'">
        <el-col :span="2">
          <el-form-item :label="$tt('label_user_type')">
            <el-radio-group v-model="userTypeInput">
              <el-radio v-for="item, index in userTypeArr" :label="item.id" :key="index">{{ item.name }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="2">
          <el-form-item :label="$tt('label_remark')" prop="remark">
            <el-input v-model="formValue.remark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <ex_header_spiler :title="$tt('label_permission_config')" style="width: 100%"></ex_header_spiler>
      <auth_tree v-model="checkboxGroupValue" :authPrivs="userPriv">

      </auth_tree>

      <!-- <el-row>
        <el-col style="width: 100%">

          <el-checkbox-group v-model="checkboxGroupValue">
            <div class="div-module" v-for="(main, mainIndex) in userPriv">
              <label>{{ main.module }}</label>

              <div :class="'div-level-1' + (sub1Index == 0 ? ' mt-32' : '')" v-for="(sub1, sub1Index) in main.children">
                <el-checkbox v-if="sub1.path && (!sub1.children || sub1.children.length == 0)" :label="sub1.path">
                  {{ $tt(sub1.name) }}
                </el-checkbox>
                <label v-else>
                  {{ $tt(sub1.name) }}
                </label>

                <div :class="'div-level-2' + (sub2Index == 0 ? ' mt-32' : '')" v-for="(sub2, sub2Index) in sub1.children">
                  <el-checkbox v-if="sub2.path && (!sub2.children || sub2.children.length == 0)" :label="sub2.path"
                    style="line-height: 32px">
                    {{ $tt(sub2.name) }}
                  </el-checkbox>
                  <label v-else>
                    {{ $tt(sub2.name) }}
                  </label>

                  <div class="div-level-3 mt-32" v-if="sub2.privs && sub2.privs.length > 0">
                    <el-checkbox v-for="(priv, privIndex) in sub2.privs" :label="priv.code" :key="privIndex">
                      {{ $tt(priv.label) }}
                    </el-checkbox>
                  </div>

                  <div :class="'div-level-3' + (sub3Index == 0 ? ' mt-32' : '')"
                    v-if="sub2.children && sub2.children.length > 0" v-for="(sub3, sub3Index) in sub2.children">
                    <el-checkbox v-if="sub3.path && (!sub3.children || sub3.children.length == 0)" :label="sub3.path">
                      {{ $tt(sub3.name) }}
                    </el-checkbox>
                    <label v-else>
                      {{ $tt(sub3.name) }}
                    </label>

                    <div class="div-level-4 mt-32 " v-if="sub3.privs && sub3.privs.length > 0">
                      <el-checkbox v-for="(priv, privIndex) in sub3.privs" :label="priv.code" :key="privIndex">
                        {{ $tt(priv.label) }}

                        <el-popover v-if="priv.description && priv.description != ''" placement="top" width="240"
                          trigger="hover">
                          {{ priv.description }}
                          <i slot="reference" class="el-icon-question" style="cursor: pointer"></i>
                        </el-popover>
                      </el-checkbox>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-checkbox-group>
        </el-col>
      </el-row> -->

    </el-form>

  </div>
    <div class="page_rela_bottom_area">
      <el-button type="primary" @click="submitForm()">{{ $tt('label_submit') }}</el-button>
      <el-button @click="goback()">{{ $tt('label_cancel') }}</el-button>
      <el-checkbox style="margin-left: 20px" v-model="checkedAll">
        {{ $tt('label_select_all') }}
      </el-checkbox>
    </div>

  </div>
</template>


<script>

import auth_tree from "./auth_tree.vue"


import srm_privs from "@/router/srm_privs.json"
import tms_privs from "@/router/tms_privs.json"
import ums_privs from "@/router/ums_privs.json"
import wms_privs from "@/router/wms_privs.json"
import oms_privs from "@/router/oms_privs.json"
import mms_privs from "@/router/mms_privs.json"
import pms_privs from "@/router/pms_privs.json"
import fms_privs from "@/router/fms_privs.json"

import pda_privs from "@/router/pda_privs.json"

export default {
  title: "label_add_role",
  components: {auth_tree},
  data() {
    return {
      title: '',
      operateType: "",

      isEdit: false,
      formValue: {
        id: "",
        remark: "",
        name: "",
        roleType: "",
        roleCode: "",
        isPrivate: "n",
      },

      rules: {
        name: [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: "blur" }],

        roleType: [
          { required: true, message: this.$tt('tip_can_no_empty'), trigger: "blur" },
        ],

        remark: [
          { required: true, message: this.$tt('tip_can_no_empty'), trigger: "blur" },
        ],
      },

      securityId: "",

      checkedAll: false,
      checkboxGroupValue: [],

      loading: false,

      userPriv: [],
      callback: null,

      roleType: '',
      roleSystemInput: '',
      roleSystemChangeTime: 0,
      roleSystemInputShow: false,
      roleSystemArr: [
        { id: 'WMS', name: this.$tt('label_wms_warehouse_system') },
        { id: 'TMS', name: this.$tt('label_tms_transport_system') },
        { id: 'OMS', name: this.$tt('label_business_back_system') },
      ],

      userTypeInput: '',
      userTypeArr: [
        { id: 'ADMIN', name: this.$tt('label_admin_user') },
        { id: 'OPERATOR', name: this.$tt('label_operator_user') }
      ]

    };
  },


  props: {

    roleScope: {
      type: String,
      defafult: ''
    },

    roleSystem: {
      type: String,
      defafult: 'ALL'
    },

  },

  created() {
    let _this = this;
    let editId = this.$route.query.id;


    // 新增页面
    if (!editId) {
      if (_this.roleSystem == 'ALL') {
        _this.roleSystemInput = 'WMS'
      }
      else {
        _this.roleSystemInput = _this.roleSystem
      }
    }

    if (_this.roleScope == 'DEFAULT') {
      _this.roleType = 'ADMIN'
      _this.roleSystemInputShow = true

      if (editId) {
        this.$tag.tagModifyLabel("label_edit_default_role")
        this.title = this.$tt("label_edit_default_role")
      } else {
        this.$tag.tagModifyLabel("label_add_default_role")
        this.title = this.$tt("label_add_default_role")
        this.userTypeInput = 'ADMIN'

      }

    } else if (_this.roleScope == 'COMPANY') {
      _this.roleType = 'OPERATOR'

      if (_this.roleSystem == 'ALL') {
        _this.roleSystemInputShow = true
      }

      if (editId) {
        this.$tag.tagModifyLabel("label_edit_role")
        this.title = this.$tt('label_edit_role')
      } else {
        this.$tag.tagModifyLabel("label_add_role")
        this.title = this.$tt('label_add_role')

      }
    } else {
      alert('roleScope error')
    }

    // if(_this.$loginUser.isMix){
    //   _this.roleSystemInputShow = true
    // }

    let tmpArr = []
    _this.loadEditForm();


  },

  watch: {

    roleSystemInput(val, old) {
      this.roleSystemChangeTime = this.roleSystemChangeTime + 1
      this.changeFormCheckbox(val)
      let editId = this.$route.query.id;
      if (editId && this.roleSystemChangeTime > 1) {
        this.checkboxGroupValue = []
      }
    },

    checkedAll(val) {
      if (val) {
        this.checkboxGroupValue = this.checkBoxAllValues;
      } else {
        this.checkboxGroupValue = [];
      }
    },

    checkboxGroupValue(val, old) {
      let _this = this;
      if (_this.initLoad) {
        return;
      }
      //  全选场景
      if (val.length == 0 && old.length == _this.checkBoxAllValues.length) {
        //
        return;
      }
      if (val.length == _this.checkBoxAllValues.length && old.length == 0) {
        //
        return;
      }
      // 对比差异
      let oldPaths = old.filter((e) => e.indexOf("/") != -1);

      // 对比差异
      let newPaths = val.filter((e) => e.indexOf("/") != -1);

      if (oldPaths.length == newPaths.length) {
        return;
      }

      // oldPaths.sort()
      // newPaths.sort()

      // 操作类型，新增了勾选，还是取消了勾选
      let addKeys = [];
      let delKeys = [];

      // 新增了勾选项
      if (oldPaths.length < newPaths.length) {
        newPaths.forEach((e) => {
          if (!oldPaths.contains(e)) {
            addKeys.push(e);
          }
        });

        //

        addKeys.forEach((path) => {
          let tmpPrivCodes = _this.pathPrivCodeMap[path];

          if (!tmpPrivCodes) {
            return;
          }
          //

          tmpPrivCodes.forEach((tmpCode) => {
            if (!_this.checkboxGroupValue.contains(tmpCode)) {
              _this.checkboxGroupValue.push(tmpCode);
            }
          });
        });
      }
      // 取消了勾选项
      else {
        oldPaths.forEach((e) => {
          if (!newPaths.contains(e)) {
            delKeys.push(e);
          }
        });

        delKeys.forEach((path) => {
          let tmpPrivCodes = _this.pathPrivCodeMap[path];

          if (!tmpPrivCodes) {
            return;
          }

          //

          tmpPrivCodes.forEach((tmpCode) => {
            // _this.checkboxGroupValue.removeObject(tmpCode)
            for (let i = 0; i < _this.checkboxGroupValue.length; i++) {
              if (_this.checkboxGroupValue[i] == tmpCode) {
                _this.checkboxGroupValue.splice(i, 1);
                break;
              }
            }
          });
        });
      }
    }

  },

  methods: {

    changeFormCheckbox(val) {

      let tmpArr = []

      let roleSystem = val

      if (roleSystem == 'WMS') {
        tmpArr = tmpArr.concat(pda_privs)
        tmpArr = tmpArr.concat(wms_privs)
      }
      else if (roleSystem == 'OMS') {
        tmpArr = tmpArr.concat(ums_privs)
        tmpArr = tmpArr.concat(oms_privs)
        tmpArr = tmpArr.concat(mms_privs)
        tmpArr = tmpArr.concat(srm_privs)
        tmpArr = tmpArr.concat(pms_privs)
        tmpArr = tmpArr.concat(fms_privs)
      }
      else if (roleSystem == 'TMS') {
        tmpArr = tmpArr.concat(tms_privs)
      }
      else {
      }

      // v-if="!(roleScope=='COMPANY' && sub2.isAdmin) "
      if (this.roleScope == 'COMPANY' && tmpArr.length > 0) {
        tmpArr = tmpArr.filter((sys, sysIndex, sysArr) => {
          sys.children = sys.children.filter((module, moduleIndex, moduleArr) => {
            module.children = module.children.filter((folder, foderIndex, folderArr) => {
              return !folder.isAdmin
            })
            return module.children.length > 0
          })
          return sys.children.length > 0
        })
      }

      this.privAccessMap = {};
      this.checkBoxAllValues = [];
      this.userPriv = tmpArr


      // const out = []
      // const outTable = (item,...ts)=>{
      //   let list = []
      //   if(!_.isEmpty(item.privs)){
      //     list = item.privs
      //   }else if(!_.isEmpty(item.children )){
      //     list = item.children 
      //   }
      //   let key = item.module || item.name || item.label
      //   let description = item.description
      //   if(!_.isEmpty(list)){
      //     for(let i = 0;i<list.length;i++){
      //       outTable(list[i],...ts,key)
      //     }
      //   }else{
      //     let nowKey = `${this.$t(key)}`
      //     if(description){
      //       nowKey += ` (${this.$t(description)})`
      //     }
      //     let o =[...ts.map(k=>this.$t(k)),nowKey].join("\t\t")
      //     // console.log(o)
      //     out.push(o)
      //   }
      // }

      // tmpArr.forEach(it=>outTable(it))
      // console.log(out.join("\n"))
      //

      // 每个权限编码要访问的 url
      let privAccessMap = {};
      // 所有的 path code、 priv code 的集合
      let checkBoxAllValues = [];
      // 每个 path 下的 privCode集合
      let pathPrivCodeMap = {};

      let fillAccessMap = (e) => {
        if (e.children && e.children.length > 0) {
          e.children.forEach((f) => {
            fillAccessMap(f);
          });
        } else {
          if (e.privs && e.privs.length > 0) {
            for (let i = 0; i < e.privs.length; i++) {
              let priv = e.privs[i];
              if (privAccessMap[priv.code]) {
                this.$message({
                  type: "error",
                  message: this.$tt('tip_duplicate_definition_button_permissions') + ",code: " + priv,
                });
                console.error(priv)
                break;
              }

              checkBoxAllValues.push(priv.code);
              privAccessMap[priv.code] = priv.access ? priv.access : [];
            }

            pathPrivCodeMap[e.path] = e.privs.map((priv) => priv.code);
          }

          if (e.path) {
            checkBoxAllValues.push(e.path);
          }
        }
      };
      this.userPriv.forEach((e) => {
        e.children.forEach((f) => {
          fillAccessMap(f);
        });
      });

      this.privAccessMap = privAccessMap;
      this.checkBoxAllValues = checkBoxAllValues;
      this.pathPrivCodeMap = pathPrivCodeMap;

    },


    loadEditForm() {
      let _this = this;
      let editId = this.$route.query.id;

      if (this.$route.params.callback) this.callback = this.$route.params.callback

      if (editId) {
        _this.operateType = this.$tt("label_modify");

        _this.formValue = {};
        _this.checkboxGroupValue = [];

        _this.initLoad = true;

        _this.$ajax({
          url: "/ums-api/user/UserRoleRpc/detail.json",
          data: { id: editId },
          success: function (responseData) {
            let arr = [];
            let data = responseData.data;

            _this.changeFormCheckbox(data.roleSystem)

            if (data.menus) {
              data.menus.forEach((kk) => {
                if (_this.checkBoxAllValues.contains(kk)) {
                  arr.push(kk);
                }
              });
            }

            if (data.btnCodes) {
              data.btnCodes.forEach((kk) => {
                if (_this.checkBoxAllValues.contains(kk)) {
                  arr.push(kk);
                }
              });
            }

            delete data.menus;
            delete data.btnCodes;
            delete data.dataUris;

            //

            _this.userTypeInput = data.roleType
            _this.roleSystemInput = data.roleSystem

            _this.formValue = data;
            _this.checkboxGroupValue = arr;

            window.setTimeout(function () {
              _this.initLoad = false;
            }, 200);
          },
        });
      } else {
        _this.operateType = this.$tt("label_new");
        _this.initLoad = false;
      }
    },

    //表单提交
    submitForm(jump) {
      var _this = this;
      //
      _this.$refs["role_form_panel"].validate(function (personValid) {
        if (personValid) {
          _this.ajaxSubmitForm();
        }
      });
    },

    //表单提交
    ajaxSubmitForm(jump) {
      var _this = this;
      if (_this.saveButtonDisabled) {
        return;
      }

      let menus = _this.checkboxGroupValue.filter((e) => e.indexOf("/") != -1);

      let btnCodes = _this.checkboxGroupValue.filter(
        (e) => e.indexOf("/") == -1
      );

      let access = [];

      btnCodes.forEach((e) => {
        if (_this.privAccessMap[e]) {
          _this.privAccessMap[e].forEach((k) => {
            if (!access.contains(k)) {
              access.push(k);
            }
          });
        }
      });

      _this.formValue.menus = menus;
      _this.formValue.btnCodes = btnCodes;
      _this.formValue.dataUris = access;

      _this.formValue.roleScope = _this.roleScope
      _this.formValue.roleType = _this.userTypeInput
      _this.formValue.roleSystem = _this.roleSystemInput

      _this.$ajax({
        url: "/ums-api/user/UserRoleRpc/saveUpdate.json",
        type: "json",
        data: _this.formValue,
        success: (responseData) => {
          _this.$message({
            type: "success",
            message: this.$tt("tip_operate_success"),
          });

          if (_this.callback) _this.callback()
          _this.$tag.tagClose()

        },
      });
    },

    handleChange(value) {
    },

    goback() {
      this.$tag.tagClose()
    },
  },
};
</script>
<style>


.mt-32 {
  margin-top: -32px;
}

.div-module label {
  font-size: 14px;
  line-height: 32px;
}

.div-module div {
  /*margin: 8px 0px 8px 0px;*/

  /*line-height: 32px;*/
}

.div-module {
  margin-left: 80px;
  /*line-height: 32px;*/
  color: #000;
  padding-bottom: 20px;
  padding-top: 20px;

  border-bottom: 1px dashed rgb(220, 223, 230);
  /*position: relative;*/
}

.div-module:last-child {
  border-bottom: none;
}

.div-level-1 {
  display: inherit;
  margin-left: 130px;
  border-bottom: 1px dashed rgb(220, 223, 230);
}

.div-level-1:last-child {
  border-bottom: none;
}

.div-level-2 {
  display: inherit;
  margin-left: 160px;
  border-bottom: 1px dashed rgb(220, 223, 230);
}

.div-level-2:last-child {
  border-bottom: none;
}

.div-level-3 {
  display: inherit;
  margin-left: 160px;
  border-bottom: 1px dashed rgb(220, 223, 230);
}

.div-level-3:last-child {
  border-bottom: none;
}

.div-level-4 {
  display: inherit;
  margin-left: 160px;
}

.div-module .el-checkbox {
  width: 150px;
  margin-right: 10px;
  line-height: 32px;
  margin-top: 0px;
  margin-bottom: 0px;
  padding-top: 0px;
  padding-bottom: 0px;
  margin-top: 0px;
  margin-bottom: 0px;

  overflow: hidden;
  box-sizing: border-box;
}

.div-module .el-checkbox .el-checkbox__label {
  box-sizing: border-box;
  padding-right: 10px;
}

/*.div-module .el-checkbox .el-checkbox__label{
    width: 120px;
    overflow-x: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }*/
</style>
